<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <span
          class="u-cursor"
          @click="$router.back()"
        >平台管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{pageTitle}}平台</el-breadcrumb-item>
    </el-breadcrumb>
    <Container class="u-pb60">
      <el-form
        class="m-form--detail"
        label-width="160px"
        :model="pageData"
        :rules="pageRules"
        ref="pageForm"
      >
        <ContainerTitle>基本信息</ContainerTitle>
        <el-form-item
          required
          prop="platformName"
          size="small"
          label="平台名称："
        >
          <el-autocomplete
            class="u-w350"
            clearable
            v-model.trim="pageData.platformName"
            :disabled="pageAction === 'detail'"
            :fetch-suggestions="platformQuerySearch"
            placeholder="请输入客户名称"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item
          prop="generalWebsite"
          size="small"
          label="普通账号登录网址："
        >
          <el-input
            class="u-w350"
            placeholder="请输入普通账号登录网址"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.generalWebsite"
          ></el-input>
          <el-button
            type="primary"
            class="u-ml10"
            v-if="pageData.generalWebsite && pageAction === 'detail'"
            @click="openWindow(pageData.generalWebsite)"
          >预览</el-button>
        </el-form-item>
        <el-form-item
          prop="mainWebsite"
          size="small"
          label="主账号登录网址："
        >
          <el-input
            class="u-w350"
            placeholder="请输入主账号登录网址"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.mainWebsite"
          ></el-input>
          <el-button
            type="primary"
            class="u-ml10"
            v-if="pageData.mainWebsite && pageAction === 'detail'"
            @click="openWindow(pageData.mainWebsite)"
          >预览</el-button>
        </el-form-item>

        <ContainerTitle>对账信息</ContainerTitle>
        <el-form-item
          prop="billingCycleValue"
          size="small"
          label="对账周期："
        >
          <el-checkbox-group
            size="small"
            :disabled="pageAction === 'detail'"
            v-model="pageData.billingCycle"
          >
            <el-checkbox label="1">月度</el-checkbox>
            <el-checkbox label="2">季度</el-checkbox>
            <el-checkbox label="3">每笔</el-checkbox>
            <el-checkbox label="4">其他</el-checkbox>
          </el-checkbox-group>
          <el-input
            v-if="pageData.billingCycle.includes('4')"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.billingCycleValue"
            class="u-w350"
            type="textarea"
            placeholder="请输入其他对账周期"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="billingWaysValue"
          size="small"
          label="对账方式："
        >
          <el-checkbox-group
            size="small"
            :disabled="pageAction === 'detail'"
            v-model="pageData.billingWays"
          >
            <el-checkbox label="1">后台</el-checkbox>
            <el-checkbox label="2">邮件</el-checkbox>
            <el-checkbox label="3">结算单</el-checkbox>
            <el-checkbox label="4">运营每日统计</el-checkbox>
            <el-checkbox label="5">其他</el-checkbox>
          </el-checkbox-group>
          <el-input
            v-if="pageData.billingWays.includes('5')"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.billingWaysValue"
            class="u-w350"
            type="textarea"
            placeholder="请输入其他对账方式"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            v-model.trim="pageData.remarks"
            :disabled="pageAction === 'detail'"
            class="u-w350"
            type="textarea"
            rows="5"
            maxlength="200"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>

        <template v-if="pageAction === 'detail'">
          <ContainerTitle>平台状态</ContainerTitle>
          <el-form-item label="平台状态：">{{mapOptionLabel(PLATFORM_STATUS_OPTION, pageData.status)}}</el-form-item>
          <el-form-item label="最后操作人：">{{pageData.updateBy}}</el-form-item>
          <el-form-item label="最后操作时间：">{{pageData.updateTime}}</el-form-item>
        </template>
      </el-form>
    </Container>
    <Affix :offset-bottom="0">
      <ButtonGroup
        isFixed
        align="right"
      >
        <el-button
          size="small"
          @click="$router.back()"
        >返回</el-button>
        <el-button
          size="small"
          type="primary"
          v-if="['create', 'edit'].includes(pageAction)"
          @click="handleEnsure"
        >确定</el-button>
      </ButtonGroup>
    </Affix>
  </div>
</template>

<script>
import ContainerTitle from "@/components/container-title";
import Container from "@/components/container";
import Affix from "@/components/affix";
import ButtonGroup from "@/components/button-group";

import { PLATFORM_STATUS_OPTION } from "@/assets/js/flow-option";
import { getStrLen, mapOptionLabel } from "@/util";

export default {
  components: {
    ContainerTitle,
    Container,
    Affix,
    ButtonGroup
  },
  data() {
    return {
      PLATFORM_STATUS_OPTION,

      pageAction: this.$route.query.action,

      customerOptions: [],

      pageData: {
        platformName: "",
        generalWebsite: "",
        mainWebsite: "",
        billingCycle: [],
        billingCycleValue: "",
        billingWays: [],
        billingWaysValue: ""
      },
      pageRules: {
        platformName: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请输入平台名称"));
            } else if (getStrLen(value) > 30) {
              callback(new Error("平台名称最多30个字符"));
            } else {
              callback();
            }
          },
          trigger: ["change", "blur"]
        },
        generalWebsite: {
          validator: (rule, value, callback) => {
            if (value && !/^https?:\/\//.test(value)) {
              callback(new Error("请输入以http或https开头的网址"));
            } else {
              callback();
            }
          },
          trigger: ["change", "blur"]
        },
        mainWebsite: {
          validator: (rule, value, callback) => {
            if (value && !/^https?:\/\//.test(value)) {
              callback(new Error("请输入以http或https开头的网址"));
            } else {
              callback();
            }
          },
          trigger: ["change", "blur"]
        },
        billingCycleValue: {
          validator: (rule, value, callback) => {
            if (getStrLen(value) > 50) {
              callback(new Error("对账周期50个字符"));
            } else {
              callback();
            }
          },
          trigger: ["change", "blur"]
        },
        billingWaysValue: {
          validator: (rule, value, callback) => {
            if (getStrLen(value) > 50) {
              callback(new Error("对账方式最多50个字符"));
            } else {
              callback();
            }
          },
          trigger: ["change", "blur"]
        }
      }
    };
  },
  computed: {
    pageTitle() {
      return {
        create: "新增",
        edit: "编辑",
        detail: "查看"
      }[this.pageAction];
    },
    submitData() {
      return {
        ...this.pageData,
        billingCycle: this.pageData.billingCycle.join(),
        billingWays: this.pageData.billingWays.join()
      };
    }
  },
  methods: {
    mapOptionLabel,

    // 平台名称搜索
    platformQuerySearch(queryString, cb) {
      let results = queryString
        ? this.platformOptions.filter(this.platformQueryFilter(queryString))
        : this.platformOptions;
      cb(results);
    },
    platformQueryFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    fetchPlatformOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/platform/get_platform",
        params: {
          productId: 0,
          customerId: 0,
          status: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.platformOptions = res.data.data.map(item => {
            return {
              ...item,
              value: item.name
            };
          });
        }
      });
    },
    // 确定
    handleEnsure() {
      if (this.pageAction === "edit") {
        this.updateDetail();
      } else {
        this.createDetail();
      }
    },
    // 新建
    createDetail() {
      this.$refs.pageForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/platform/add",
            data: this.submitData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("新建成功！");
              this.$router.back();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 编辑
    updateDetail() {
      this.$refs.pageForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/platform/update",
            data: this.submitData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("修改成功！");
              this.$router.back();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 详情
    getDetail() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/platform/get_by_id",
        params: {
          platformId: this.$route.query.id
        }
      }).then(res => {
        if (res.data.code === 0) {
          let data = res.data.data;
          if (this.pageAction === "edit") {
            let {
              id,
              platformName,
              generalWebsite,
              mainWebsite,
              billingCycle,
              billingCycleValue,
              billingWays,
              billingWaysValue,
              remarks
            } = res.data.data;
            data = {
              id,
              platformName,
              generalWebsite,
              mainWebsite,
              billingCycle,
              billingCycleValue,
              billingWays,
              billingWaysValue,
              remarks
            };
          }
          this.pageData = {
            ...data,
            billingCycle: data.billingCycle.split(","),
            billingWays: data.billingWays.split(",")
          };
        }
      });
    },
    openWindow(url) {
      if (url) {
        window.open(url);
      }
    }
  },
  created() {
    this.fetchPlatformOptions();
    if (["edit", "detail"].includes(this.pageAction)) {
      this.getDetail();
    }
  }
};
</script>